#import "NetWork.h"
#import "AFNetworking.h"
#import "CYLTabBarController.h"
#import "LoginViewController.h"

@interface NetWork ()

@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;

@end

@implementation NetWork

+(void)sendGetUrl:(NSString *)url withParams:(NSDictionary *)params success:(successBlock) success failure:(failureBlock)failure
{
    
    NSString *urlStr = [[NSString stringWithFormat:@"%@%@", BASEURL, url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    session.requestSerializer.timeoutInterval = 7;
    session.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [session GET:urlStr parameters:params headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [session invalidateSessionCancelingTasks:NO resetSession:YES];
        
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 200) {
            success(responseObject[@"data"]);
        }else{
            failure(nil);
            [MBProgressHUD showError:responseObject[@"msg"] toView:nil];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(error.code == -1001){
        }else if(error.code == -1011){
            [MBProgressHUD showError:@"服务器出错了" toView:nil];
        }else if(error.code == -1009){
            [MBProgressHUD showError:@"网络不通畅" toView:nil];
        }else{
            [MBProgressHUD showError:@"网络较差，请稍后重试" toView:nil];
        }
        NSLog(@"error api:%@", url);
        failure(error);
        [session invalidateSessionCancelingTasks:NO resetSession:YES];
    }];
 
}

+(void)loadCitysWithKeyWord:(NSString *)keyword subdistrict:(NSInteger)subdistrict success:(successBlock) success failure:(failureBlock)failure;{
    NSString *urlStr = [[NSString stringWithFormat:@"https://restapi.amap.com/v3/config/district?keywords=%@&subdistrict=%ld&key=1174f513028d78c5eff6272178c247c3", keyword, subdistrict] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    session.requestSerializer.timeoutInterval = 7;
    session.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [session GET:urlStr parameters:nil headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [session invalidateSessionCancelingTasks:NO resetSession:YES];
        
        NSInteger code = [responseObject[@"infocode"] integerValue];
        if (code == 10000) {
            NSArray *arr = responseObject[@"districts"];
            if (arr.count > 0) {
                NSDictionary *dict = arr[0];
                success(dict[@"districts"]);
            }else{
                
                [MBProgressHUD showError:@"未查询到数据" toView:nil];
                failure(nil);
            }
            
        }else{
            failure(nil);
            [MBProgressHUD showError:responseObject[@"info"] toView:nil];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(error.code == -1001){
        }else if(error.code == -1011){
            [MBProgressHUD showError:@"服务器出错了" toView:nil];
        }else if(error.code == -1009){
            [MBProgressHUD showError:@"网络不通畅" toView:nil];
        }else{
            [MBProgressHUD showError:@"网络较差，请稍后重试" toView:nil];
        }
        failure(error);
        [session invalidateSessionCancelingTasks:NO resetSession:YES];
    }];
}


+(void)uploadImageWithImage:(UIImage *)image success:(successBlock) success failure:(failureBlock)failure{
    NSString *urlStr = [[NSString stringWithFormat:@"%@fy/fy_img.php", BASEURL] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    
    session.responseSerializer = [AFJSONResponseSerializer serializer];
    
    NSDictionary *dict = @{
        @"uid": [User sharedUser].userId,
        @"token": [User sharedUser].token
    };
    [session POST:urlStr parameters:dict headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *imageData = UIImageJPEGRepresentation(image,0.3);
        NSDate *date = [NSDate date];
        NSString *dateStr = [date stringWithFormat:@"yyyyMMddHHmmss"];
        [formData appendPartWithFileData:imageData name:@"fle" fileName:[NSString stringWithFormat:@"%@.jpg", dateStr] mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [session invalidateSessionCancelingTasks:NO resetSession:YES];
        NSInteger code = [responseObject[@"code"] integerValue];
        if (code == 200) {
            success(responseObject[@"data"]);
        }else{
            failure(nil);
            [MBProgressHUD showError:responseObject[@"msg"] toView:nil];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
        [MBProgressHUD showError:@"接口错误" toView:nil];
        [session invalidateSessionCancelingTasks:NO resetSession:YES];
    }];
    

}


@end
